<?php

namespace Mlym\CodeGeneration\Middleware;

use EasySwoole\ORM\Utility\Schema\Column;
use EasySwoole\ORM\Utility\Schema\Table;
use Mlym\CodeGeneration\Middleware\Bean\Module\ModuleBean;
use Mlym\CodeGeneration\Middleware\Bean\Module\SchemaColumnBean;

/**
 * table生成
 * Class TableGeneration
 * @author Ryan <43352901@qq.com>
 * @date 6/14/21 1:01 PM
 * @package Mlym\CodeGeneration\Middleware
 */
class TableGeneration
{
    private $module;

    public function __construct(ModuleBean $module)
    {
        $this->module = $module;
    }

    /**
     * 构建Table对象
     * @return Table
     */
    public function generate()
    {
        $columns = $this->module->getSchema();
        /**
         * 初始化数据库表对象
         */
        $table = new Table($this->module->getTableName());
        /**
         * 配置模块备注信
         */
        $table->setTableComment($this->module->getComment());
        /**
         * 配置字段信息
         */
        foreach ($columns as $column) {
            if ($column instanceof SchemaColumnBean) {
                $columnObj = $this->getColumn($column);
                $table->addColumn($columnObj);
            }
        }
        return $table;
    }

    /**
     * 将字段信息转换 Column 对象
     * @param SchemaColumnBean $columnBean
     * @return Column
     */
    private function getColumn(SchemaColumnBean $columnBean): Column
    {
        $column = new Column($columnBean->getName(), $columnBean->getType());
        $column->setColumnComment($columnBean->getComment());
        $column->setColumnLimit($columnBean->getLength());
        $columnBean->getDefault() && $column->setDefaultValue($columnBean->getDefault());
        $columnBean->isNull() && $column->setIsNotNull(!$columnBean->isNull());
        $columnBean->isAutoIncrement() && $column->setIsAutoIncrement($columnBean->isAutoIncrement());
        $columnBean->isIsPrimary() && $column->setIsPrimaryKey(true);
        return $column;
    }

}